package com.base.cn.platform.os.service.qa.record;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.service.CommonSetCreateUserDataService;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.dao.qa.record.QaTeacherCashRecordDao;
import com.base.cn.platform.os.entity.qa.record.QaGainAttendRecord;
import com.base.cn.platform.os.entity.qa.record.QaRecordBaseEntity;
import com.base.cn.platform.os.entity.qa.record.QaTeacherCashRecord;
import com.base.cn.platform.os.entity.qa.record.QaTeacherCommission;
import com.base.cn.platform.os.service.manage.sysUser.SysUserService;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 老师问答分成提现记录Biz
 *
 * @author s.li
 * @date 2018/11/27
 */
@Service
public class QaTeacherCashRecordBiz extends BaseBiz<QaTeacherCashRecord, QaTeacherCashRecordDao> {

    @Autowired
    private QaTeacherCommissionBiz qaTeacherCommissionBiz;
    @Autowired
    private QaGainAttendRecordBiz qaGainAttendRecordBiz;
    @Autowired
    private CommonSetCreateUserDataService<QaTeacherCashRecord> commonSetCreateUserDataService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysTeacherService sysTeacherService;

    /**
     * 创建老师提现记录
     * @param teacherId 老师ID
     * @param accountType 提现的账号类型
     * @param account 账号
     * @param realName 账号名真实姓名
     * @param createUserId 创建人ID
     * @param recordType 记录类型，1问答分成，2旁听分成
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void createQaTeacherCashRecord(List<? extends QaRecordBaseEntity> dataList, BigDecimal teacherId,
                                          int accountType,
                                          String account,
                                          String realName,
                                          BigDecimal createUserId,
                                          int recordType){

        if(ObjectUtils.isNotEmpty(dataList)){
            QaTeacherCashRecord record = new QaTeacherCashRecord();
            record.setTeacherId(teacherId);
            record.setCreateUserId(createUserId);
            record.setAccountType(accountType);
            record.setAccount(account);
            record.setRealName(realName);
            double price = 0;
            if(recordType==1){
                List<QaTeacherCommission> qaTeacherCommissionList = new ArrayList<>();
                for(int i=0 ;i<dataList.size();i++){
                    QaTeacherCommission teacherCommission = (QaTeacherCommission)dataList.get(i);
                    price += teacherCommission.getPrice().doubleValue();
                    qaTeacherCommissionList.add(teacherCommission);
                }
                String ids = qaTeacherCommissionList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
                QaTeacherCommission commission = new QaTeacherCommission();
                commission.setStatus(2);
                commission.setRecordId(record.getId());
                qaTeacherCommissionBiz.updateByWhereSql(commission," id in ("+ids+")");
            }else if(recordType==2){
                List<QaGainAttendRecord> qaGainAttendRecordList = new ArrayList<>();
                for(int i=0 ;i<dataList.size();i++){
                    QaGainAttendRecord qaTeacherCommission = (QaGainAttendRecord)dataList.get(i);
                    price += qaTeacherCommission.getAmount().doubleValue();
                    qaGainAttendRecordList.add(qaTeacherCommission);
                }
                String ids = qaGainAttendRecordList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
                QaGainAttendRecord qaTeacherCommission = new QaGainAttendRecord();
                qaTeacherCommission.setStatus(2);
                qaTeacherCommission.setRecordId(record.getId());
                qaGainAttendRecordBiz.updateByWhereSql(qaTeacherCommission," id in ("+ids+")");
            }
            record.setPrice(price);
            record.setStatus(1);
            record.setRecordType(recordType);
            this.save(record);
        }
    }

    /**
     * 分成查询老师申请提现记录
     * @param teacherCashRecord 查询对象
     * @param page 分页对象
     * @return PageInfo<QaTeacherCashRecord>
     */
    public PageInfo<QaTeacherCashRecord> findQaTeacherCashRecordPage(QaTeacherCashRecord teacherCashRecord, Pagination page) {
        String whereSql = this.getWhereSql(teacherCashRecord);
        PageInfo<QaTeacherCashRecord> teacherCashRecordPageInfo = this.findPage(whereSql,page,null);
        this.setExtendData(teacherCashRecordPageInfo.getList(),teacherCashRecord);
        return teacherCashRecordPageInfo;
    }

    /**
     * 获取提现申请详情
     * @param teacherCashRecord 查询条件
     * @return QaTeacherCashRecord
     */
    public QaTeacherCashRecord getTeacherCashRecordInfo(QaTeacherCashRecord teacherCashRecord) {
        String whereSql = this.getWhereSql(teacherCashRecord);
        QaTeacherCashRecord cashRecord = this.findOne(whereSql,null);
        this.setExtendData(cashRecord,teacherCashRecord);
        return cashRecord;
    }

    /**
     * 设置数据扩展数据
     * @param qaTeacherCashRecord
     * @param condition 条件对象
     */
    private void setExtendData(QaTeacherCashRecord qaTeacherCashRecord,QaTeacherCashRecord condition){
        if(ObjectUtils.isNotEmpty(qaTeacherCashRecord)){
            this.setExtendData(Collections.singletonList(qaTeacherCashRecord),condition);
        }
    }

    /**
     * 设置数据扩展数据
     * @param teacherCashRecordList
     * @param teacherCashRecord
     */
    private void setExtendData(List<QaTeacherCashRecord> teacherCashRecordList,
                              QaTeacherCashRecord teacherCashRecord){
        if(ObjectUtils.isNotEmpty(teacherCashRecordList)){
            if(teacherCashRecord.isCreateUserData()){
                commonSetCreateUserDataService.setSysUserData(sysUserService,teacherCashRecordList,true);
            }
            if(teacherCashRecord.isExamineUserData()){
                String userIds = teacherCashRecordList.stream().filter(e->!DataUtil.idIsNotNull(e.getExamineUserId())).map(e->e.getExamineUserId().toString()).collect(Collectors.joining(","));
                Map<BigDecimal,Map<String,Object>> userMap = sysUserService.findSysUserMapByUserIds(userIds,false,false,false);
                if(ObjectUtils.isNotEmpty(userMap)){
                    teacherCashRecordList.forEach(e->{
                        e.setTeacher(userMap.get(e.getExamineUserId()));
                    });
                }
            }
            if(teacherCashRecord.isTeacherData()){
                String teacherIds = teacherCashRecordList.stream().map(e->e.getTeacherId().toString()).collect(Collectors.joining(","));
                Map<BigDecimal, Map<String,Object>> teacherMap = sysTeacherService.findSysTeacherToMapByIds(teacherIds,false,false,false,false,false);
                if(ObjectUtils.isNotEmpty(teacherMap)){
                    teacherCashRecordList.forEach(e->{
                        e.setTeacher(teacherMap.get(e.getTeacherId()));
                    });
                }
            }
        }
    }

    /**
     * 获取查询SQL
     * @param teacherCashRecord
     * @return
     */
    private String getWhereSql(QaTeacherCashRecord teacherCashRecord){
        StringBuilder whereSql = new StringBuilder(" 1=1");
        if(ObjectUtils.isNotEmpty(teacherCashRecord)){
            if(DataUtil.idIsNotNull(teacherCashRecord.getId())){
                whereSql.append(" and id =").append(teacherCashRecord.getId());
            }
            if(DataUtil.idIsNotNull(teacherCashRecord.getTeacherId())){
                whereSql.append(" and teacherId = ").append(teacherCashRecord.getTeacherId());
            }
            if(ObjectUtils.isNotEmpty(teacherCashRecord.getRecordType())){
                whereSql.append(" and recordType = ").append(teacherCashRecord.getRecordType());
            }
            if(ObjectUtils.isNotEmpty(teacherCashRecord.getStatus())){
                whereSql.append(" and status = ").append(teacherCashRecord.getStatus());
            }
            if(ObjectUtils.isNotEmpty(teacherCashRecord.getStartTime())){
                whereSql.append(" and createTime >= '").append(DateUtils.format(teacherCashRecord.getStartTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if(ObjectUtils.isNotEmpty(teacherCashRecord.getEndTime())){
                whereSql.append(" and createTime <= '").append(DateUtils.format(teacherCashRecord.getEndTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
        }
        return whereSql.toString();
    }
}
